package com.lovver.atoms.springboot.autoconfigue;

import com.lovver.atoms.config.AtomsBean;
import com.lovver.atoms.config.AtomsSpringConfig;
import com.lovver.atoms.core.CacheChannel;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@Configuration
@EnableConfigurationProperties(AtomsProperties.class)
@ConditionalOnClass(AtomsBean.class)
@ConditionalOnProperty(prefix = "atoms", value = "enabled", matchIfMissing = true)
@AutoConfigureBefore(CacheChannel.class)
public class AtomsAutoConfiguration {

    @Autowired
    private AtomsProperties atomsProperties;


    @Bean(name="atomsSpringConfig")
    @ConditionalOnMissingBean(AtomsSpringConfig.class)
    public AtomsSpringConfig initAtomsSpringConfig() {
        AtomsSpringConfig atomsSpringConfig = null;
        if (StringUtils.isNotEmpty(atomsProperties.getLocation())) {
            ApplicationContext ac=new ClassPathXmlApplicationContext(new String[]{"classpath:"+atomsProperties.getLocation()});
            atomsSpringConfig=ac.getBean(AtomsSpringConfig.class);
        } else {
            atomsSpringConfig = new AtomsSpringConfig();
            atomsSpringConfig.setAtomsBean(atomsProperties);
        }

        return atomsSpringConfig;
    }
}